#include <iostream>
#include "log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <strings.h>
#include <string>
#include <cstring>

Log lg;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

const uint16_t defaultport = 8080;
const string defaultip = "0.0.0.0";

class udpServer
{
public:
    udpServer(const uint16_t &port = defaultport, const string &ip = defaultip)
        : port_(port), ip_(ip), sockfd_(0)
    {
    }

    void Init()
    {
        // 1.创建套接字文件描述符
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ == -1)
        {
            lg(Fatal, "socket creat fail, sockfd:%d", sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket creat success, sockfd:%d", sockfd_);

        // 2.bind端口号和ip
        struct sockaddr_in sk;
        bzero(&sk, sizeof(sk)); // 初始化0
        sk.sin_family = AF_INET;
        sk.sin_port = htons(port_);
        sk.sin_addr.s_addr = inet_addr(ip_.c_str()); // 由于ip地址设置为0所以不需要转换为网络序列

        socklen_t len = sizeof(sk);
        if (bind(sockfd_, (struct sockaddr *)&sk, len) < 0)
        {
            lg(Fatal, "bind fail, errno:%d, err string:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno:%d, err string:%s", errno, strerror(errno));
    }

    void Run()
    {
        isrunning_ = true;

        while (isrunning_)
        {

            // 接收消息
            char buffer[1024];
            struct sockaddr_in client;
            bzero(&client, sizeof(client));
            socklen_t len = sizeof(client);
            int n = recvfrom(sockfd_, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client, &len);
            

            if(n<0)
            {
                lg(Warning,"recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            buffer[n] = 0;
            cout << "server get massge:" << buffer << endl;

            // 处理数据
            string send = "server echo@ " + string(buffer);

            //发送数据
            sendto(sockfd_,send.c_str(),send.size(),0,(struct sockaddr *)&client, len);
        }
    }

    ~udpServer() 
    {
        close(sockfd_);
    }

private:
    int sockfd_; // 套接字描述符
    uint16_t port_;
    std::string ip_;

    bool isrunning_;
};